﻿using System.Windows;
using System.Collections.Generic;
using DSPL.Services;
using DSPL.Contracts;
using DSPL.Common;
using System.Data;
using DSPL.Services.Services;
using DSPL.Contracts.Common;
using DSPL.Contracts.ViewModel;
using DSPL.Contracts.Command;
using DSPL.Finac.Common;
using DSPL.Common.Classes;
using System;
using DSPL.Contracts.Interfaces;
using System.Windows.Input;
using DSPL.Services.Rules;

namespace DSPL.Finac.ViewModel
{
    public class QuotationViewModel : BaseViewModel
    {
        private bool isReferenceNoFocused;
        private bool isPurchaseOrderNoFocused;
        private bool isCurrencyCodeFocused;
        private bool isDebtorCodeFocused;
        private bool isLocationCodeFocused;
        private bool isRepCodeFocused;
        private bool isCostCodeFocused;
        private bool isExchangeRateFocused;
        private bool isTransactionDateFocused;
        private DataRow drItemRow;
        private DataTable _dtQuotationTax;
        private ICommand _refreshCurrencyData;
       

        #region Define properties

        public bool IsPurchaseOrderNoFocused
        {
            get { return isPurchaseOrderNoFocused; }
            set
            {
                isPurchaseOrderNoFocused = value;
                this.OnPropertyChanged("IsPurchaseOrderNoFocused");
            }
        }

        public bool IsCurrencyCodeFocused
        {
            get { return isCurrencyCodeFocused; }
            set
            {
                isCurrencyCodeFocused = value;
                this.OnPropertyChanged("IsCurrencyCodeFocused");

            }
        }

        public bool IsDebtorCodeFocused
        {
            get { return isDebtorCodeFocused; }
            set
            {
                isDebtorCodeFocused = value;
                this.OnPropertyChanged("IsDebtorCodeFocused");

            }
        }

        public bool IsLocationCodeFocused
        {
            get { return isLocationCodeFocused; }
            set
            {
                isLocationCodeFocused = value;
                this.OnPropertyChanged("IsLocationCodeFocused");

            }
        }

        public bool IsCostCodeFocused
        {
            get { return isCostCodeFocused; }
            set
            {
                isCostCodeFocused = value;
                this.OnPropertyChanged("IsCostCodeFocused");

            }
        }

        public bool IsExchangeRateFocused
        {
            get { return isExchangeRateFocused; }
            set
            {
                isExchangeRateFocused = value;
                this.OnPropertyChanged("IsExchangeRateFocused");

            }
        }

        public bool IsTransactionDateFocused
        {
            get { return isTransactionDateFocused; }
            set
            {
                isTransactionDateFocused = value;
                this.OnPropertyChanged("IsTransactionDateFocused");

            }
        }

        public bool IsReferenceNoFocused
        {
            get { return isReferenceNoFocused; }
            set
            {
                isReferenceNoFocused = value;
                this.OnPropertyChanged("IsReferenceNoFocused");

            }
        }

        public bool IsRepCodeFocused
        {
            get { return isRepCodeFocused; }
            set
            {
                isRepCodeFocused = value;
                this.OnPropertyChanged("IsRepCodeFocused");

            }
        }

        
        public DataRow ItemSelectedRow
        {
            get
            {
                return drItemRow;
            }
            set
            {
                drItemRow = value;
                OnPropertyChanged("ItemSelectedRow");
            }
        }

        public DataTable DtQuotationTax
        {
            get { return _dtQuotationTax; }
            set
            {
                _dtQuotationTax = value;
                this.OnPropertyChanged("DtQuotationTax");
            }
        }


        #endregion

        # region Commands

        public ICommand RefreshCurrencyData
        {
            get
            {
                if (this._refreshCurrencyData == null)
                {
                    this._refreshCurrencyData = new RelayCommand(RefreshCurrencyDataExecuted);
                }
                return this._refreshCurrencyData;
            }
        }
        #endregion


        #region Constructor

        public QuotationViewModel()
            : base()
        {
            MessageTitle = "Quotation";
        }

        #endregion
        /// <summary>
        /// Validate mandatory data before save
        /// </summary>
        /// <param name="obj"></param>
        protected override void PreDataValidateExecuted(object obj)
        {
            IsPurchaseOrderNoFocused = false;
            IsCurrencyCodeFocused = false;
            IsDebtorCodeFocused = false;
            IsLocationCodeFocused = false;
            IsCostCodeFocused = false;
            IsExchangeRateFocused = false;
            IsTransactionDateFocused = false;
            IsReferenceNoFocused = false;
            IsRepCodeFocused = false;
                       
            var messageService = new MessageService();
            if (FormMode != Modes.New)
            {
                if (CurrentRow["RefNo"].ToString().Trim() == string.Empty)
                {
                    messageService.ShowMessage(MessageText.ReferenceNoNotEmpty, MessageTitle, MessageType.InfoOK);
                    IsReferenceNoFocused = true;
                    this.IsValid = false;
                    return;
                }
            }

            if (CurrentRow["TxnDate"] == DBNull.Value)
            {
                messageService.ShowMessage(MessageText.TransactionDateNotEmpty, MessageTitle, MessageType.InfoOK);
                IsTransactionDateFocused = true;
                this.IsValid = false;
                return;
            }
            else
            { 
                var stockRules = new StockRulesService();
                if (!stockRules.ValidateStockTransactionDate(Convert.ToDateTime(CurrentRow["TxnDate"]), CurrentRow["RefNo"].ToString().Trim(), BlockBackDatedTransaction, ReportGroup))
                {
                    IsTransactionDateFocused = true;
                    this.IsValid = false;
                    return;
                }
            }
            if (CurrentRow["DebPk"] == DBNull.Value || Convert.ToInt32(CurrentRow["DebPk"]) == 0)
            {
                messageService.ShowMessage(MessageText.DebtorCodeNotEmpty, MessageTitle, MessageType.InfoOK);
                IsDebtorCodeFocused = true;
                this.IsValid = false;
                return;
            }
            else
            {
                var masterReadService = new MasterReadService();
                if (!masterReadService.IsDebtorActive(Convert.ToInt32(CurrentRow["DebPk"])))
                {
                    messageService.ShowMessage(MessageText.DebtorNotActive, MessageTitle, MessageType.InfoOK);
                    IsDebtorCodeFocused = true;
                    this.IsValid = false;
                    return;
                }
            }

            if (CurrentRow["LocationPk"] == DBNull.Value || Convert.ToInt32(CurrentRow["LocationPk"]) == 0)
            {
                messageService.ShowMessage(MessageText.LocationNotEmpty, MessageTitle, MessageType.InfoOK);
                IsLocationCodeFocused = true;
                this.IsValid = false;
                return;
            }

            if (CurrentRow["CostPk"] == DBNull.Value || Convert.ToInt32(CurrentRow["CostPk"]) == 0)
            {
                messageService.ShowMessage(MessageText.CostCodeNotEmpty, MessageTitle, MessageType.InfoOK);
                IsCostCodeFocused = true;
                this.IsValid = false;
                return;
            }

            if (CurrentRow["CurRate"] == DBNull.Value || Convert.ToInt32(CurrentRow["CurRate"]) == 0)
            {
                messageService.ShowMessage(MessageText.CurrencyRateNotZero, MessageTitle, MessageType.InfoOK);
                IsExchangeRateFocused = true;
                this.IsValid = false;
                return;
            }

            if (CurrentRow["RepPk"] == DBNull.Value || Convert.ToInt32(CurrentRow["RepPk"]) == 0)
            {
                messageService.ShowMessage(MessageText.LocationNotEmpty, MessageTitle, MessageType.InfoOK);
                IsRepCodeFocused  = true;
                this.IsValid = false;
                return;
            }


            if (!ValidateTaxRegistration())
            {
                this.IsValid = false;
                return;
            }

            if (!CheckItemStatus())
            {
                this.IsValid = false;
                return;
            }

            if (!CheckTaxCombinationStatus())
            {
                this.IsValid = false;
                return;
            }


            var transReadService = new TransactionReadService();
            if (!transReadService.ValidateQuotation(FormMode, (CurrentRow["QuoPk"]==DBNull.Value)?0: Convert.ToInt32(CurrentRow["QuoPk"])))
            {
                this.IsValid = false;
                return;
            }
            
            if (DtChildTransaction.Select("ItemCode<>'' AND (SellPrice> 0.00 AND Qty >0.00)").Length == 0)
            {
                messageService.ShowMessage(MessageText.NoValidData, MessageTitle, MessageType.InfoOK);
                this.IsValid = false;
                return;
            }

            for (int i = DtChildTransaction.Rows.Count - 1; i >= 0; i--)
            {
                if (string.IsNullOrEmpty(DtChildTransaction.Rows[i]["ItemCode"].ToString()) || (DtChildTransaction.Rows[i]["Qty"]) == DBNull.Value || (DtChildTransaction.Rows[i]["SellPrice"]) == DBNull.Value)
                    DtChildTransaction.Rows[i].Delete();
            }
            DtChildTransaction.AcceptChanges();

            CalculateAmounts();

            double currencyRate = Convert.ToDouble(CurrentRow["CurRate"]);
            CurrentRow["TxnType"] = "20";
            CurrentRow["BTotalDis"] = Math.Round((CurrentRow["TotalDis"]==DBNull.Value ?0.00 : Convert.ToDouble(CurrentRow["TotalDis"])) * currencyRate, 2);
            CurrentRow["BTotalTax"] = Math.Round((CurrentRow["TotalTax"] == DBNull.Value ? 0.00 : Convert.ToDouble(CurrentRow["TotalTax"])) * currencyRate, 2);
            CurrentRow["BTotalAmt"] = Math.Round((CurrentRow["TotalAmt"] == DBNull.Value ? 0.00 : Convert.ToDouble(CurrentRow["TotalAmt"])) * currencyRate, 2);

            int sequenceNo = 1;
            foreach (DataRow drDataDetail in DtChildTransaction.Rows)
            {
                drDataDetail["TxnDate"] = CurrentRow["TxnDate"];
                drDataDetail["BalQty"] = drDataDetail["Qty"];
                drDataDetail["TxnType"] = "20";
                drDataDetail["SeqNo"] = sequenceNo;
                sequenceNo += 1;
            }

            this.IsValid = true;
        }

        protected override void RefreshExternalDataObjectsExecueted(object obj)
        {
            base.RefreshExternalDataObjectsExecueted(obj);
           
           
            if (FormMode == Modes.New)
            {
                var masterReadService = new MasterReadService();
                CurrentRow["TxnDate"] = DateTime.Now;
                CurrentRow["TaxReg"] = 1;
                CurrentRow["CurPk"] = masterReadService.GetCurrencyKey(GlobalVariables.BaseCurrency);
                CurrentRow["CurRate"] = 1.00;

                var commonReadService = new CommonReadService();
                CurrentRow["CostPk"] = commonReadService.GetUserWiseCostCenter();
                CurrentRow["LocationPk"] = commonReadService.GetUserWiseLocation();
                OnPropertyChanged("CurrentRow");
            }

            LoadTransactionSpecificData();
            
        }

        protected override void PreDataDelValidationExecuted(object obj)
        {
            if (!ValidateTransactions())
            {
                this.IsValid = false;
            }
        }
       
        private void LoadTransactionSpecificData()
        {
            if (CurrentRow["QuoPk"] != DBNull.Value)
            {
                var QuotationKey = Convert.ToInt32(CurrentRow["QuoPk"]);
                var getTransactionData = new TransactionReadService();
                DtQuotationTax = getTransactionData.GetQuotationTaxData(QuotationKey);
            }
        }

        protected override void AddAddionalReportParametersExecuted(object obj)
        {
            base.AddAddionalReportParametersExecuted(obj);

            if (AdditionalReportParameters == null)
            {
                AdditionalReportParameters = new List<IReportParameters>();
            }
            AdditionalReportParameters.Add(new ReportParameters() { ParameterIndex = 8, ParameterName = "VatCompanyTaxNo", InputValue = GlobalVariables.VatCompanyTaxNo });
        }

        private void RefreshCurrencyDataExecuted(object obj)
        {
            TxtCurrency txtCurrency = (TxtCurrency)obj;
            CurrentRow["CurRate"] = txtCurrency.CurrencyRate;
            this.OnPropertyChanged("CurrentRow");
        }

        private bool ValidateTransactions()
        {
            var transactionReadService = new TransactionReadService();

            if (transactionReadService.ValidateQuotation(FormMode, Convert.ToInt32(CurrentRow["QuoPk"])))
            {
                return true;
            }
            else
            {
                return false;
            }

        }

        private bool ValidateTaxRegistration()
        {
            return true;
        }

        private bool CheckItemStatus()
        {
            var masterReadService = new MasterReadService();
            var messageService = new MessageService();
            foreach (DataRow drGridData in DtChildTransaction.Rows)
            {
                string itemCode = Convert.ToString(drGridData["ItemCode"]);

                if (itemCode == string.Empty)
                {
                    continue;
                }
                else
                {
                    if (!masterReadService.IsItemActive(Convert.ToInt32(drGridData["ItemPk"])))
                    {
                        messageService.ShowMessage("Inactive item is selected. Please change to enter transactions.\nItem Code:" + itemCode, MessageType.InfoOK);
                        return false;
                    }
                }

            }
            return true;
        }

        private bool CheckTaxCombinationStatus()
        {
            var masterReadService = new MasterReadService();
            var messageService = new MessageService();
            foreach (DataRow drGridData in DtChildTransaction.Rows)
            {
                string taxComCode = Convert.ToString(drGridData["TaxComCode"]);

                if (taxComCode == string.Empty)
                {
                    continue;
                }
                else
                {
                    if (!masterReadService.IsTaxCombinationActive(Convert.ToInt32(drGridData["TaxComPk"])))
                    {
                        messageService.ShowMessage("Inactive tax combination is selected. Please change to enter transactions. Tax Combination Code:" + taxComCode, MessageType.InfoOK);
                        return false;
                    }
                }

            }
            return true;
        }

        private void CalculateAmounts()
        {

        }
    }
}


